package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"net/http"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/common/actions"
	"tuowei.com/pkg/xlog"
)

type SysBalanceDetail struct {
	api.Api
	Base
}

func (e SysBalanceDetail) GetPages(c *gin.Context) {
	s := service.SysBalanceDetail{}
	req := dto.SysBalanceDetailGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	if req.BuyerId == 0 {
		err, req.BuyerId = e.GetUser(&e.Api)
		if err != nil {
			xlog.Error(err)
			e.Error(401, err, err.Error())
			return
		}
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	var count int64
	list := make([]models.SysBalanceDetail, 0)

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	listresp := make([]GetPagesBalanceDetailResp, 0)
	for _, sc := range list {
		sr := GetPagesBalanceDetailResp{}
		sr.Id = sc.Id
		sr.BuyerId = sc.BuyerId
		sr.Title = sc.Title
		sr.BalanceChange = sc.BalanceChange
		sr.Change = sc.Change
		sr.BalanceSum = sc.BalanceSum
		sr.CreatedTime = sc.CreatedAt.Format("2006.01.02 15:04:05")
		listresp = append(listresp, sr)
	}

	e.PageOK(listresp, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// 增加积分记录
func (score SysBalanceDetail) AddBalanceDetail(ctx *gin.Context) {
	s := service.SysBalanceDetail{}
	req := dto.SysBalanceDetailInsertReq{}
	err := score.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		score.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(ctx), user.GetUserName(ctx))

	if req.BuyerId == 0 {
		err, req.BuyerId = score.GetUser(&score.Api)
		if err != nil {
			xlog.Error(err)
			score.Error(401, err, err.Error())
			return
		}
	}

	err = s.Insert(&req)
	if err != nil {
		score.Logger.Error(err)
		score.Error(500, err, err.Error())
		return
	}
	score.OK(req.GetId(), "创建成功")
}

type GetPagesBalanceDetailResp struct {
	models.SysBalanceDetail
	CreatedTime string `json:"created_time" gorm:"comment:创建时间"`
}
